package com.library.handler;



import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.library.constant.MessageConstant;
import com.library.exception.BaseException;
import com.library.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getCode(),ex.getMessage());
    }

    /**
     * 处理参数校验异常
     * @param ex
     * @return
     */
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public ResponseEntity<List<String>> handleValidationException(MethodArgumentNotValidException ex) {
//        List<String> errors = ex.getBindingResult().getFieldErrors()
//                .stream()
//                .map(error -> error.getField() + ": " + error.getDefaultMessage())
//                .collect(Collectors.toList());
//        return ResponseEntity.badRequest().body(errors);
//    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<List<String>> handleValidationException(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.toList());
        return Result.error(400,"Validation Exception", errors);
    }


    /**
     * 处理请求参数格式错误异常
     * @param ex
     * @return
     */
//    @ExceptionHandler(HttpMessageNotReadableException.class)
//    public ResponseEntity<List<String>> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
//        List<String> errorMsg = new ArrayList<>();
//        Throwable rootCause = ex.getRootCause();
//        if (rootCause instanceof InvalidFormatException) {
//            InvalidFormatException ife = (InvalidFormatException) rootCause;
//            String fieldName = ife.getPath().get(0).getFieldName(); // 获取出错字段名
//            String error = String.format("字段 '%s' 格式错误: %s", fieldName, ife.getOriginalMessage());
//            errorMsg.add(error);
//            return ResponseEntity.badRequest().body(errorMsg);
//        }
//        if (rootCause instanceof IllegalArgumentException) {
//            IllegalArgumentException iae = (IllegalArgumentException) rootCause;
//            String error = String.format("参数错误: %s", iae.getMessage());
//            errorMsg.add(error);
//            return ResponseEntity.badRequest().body(errorMsg);
//        }
//        if(rootCause instanceof DateTimeParseException){
//            DateTimeParseException dtpe = (DateTimeParseException) rootCause;
//            String error = String.format("日期格式错误: %s", dtpe.getMessage());
//            errorMsg.add(error);
//            return ResponseEntity.badRequest().body(errorMsg);
//        }
//        String error = String.format("请求参数格式错误: %s", ex.getMessage());
//        errorMsg.add(error);
//        return ResponseEntity.badRequest().body(errorMsg);
//    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        Throwable rootCause = ex.getRootCause();
        if(rootCause instanceof DateTimeParseException){
            DateTimeParseException dtpe = (DateTimeParseException) rootCause;
            String error = String.format("日期格式错误: %s", dtpe.getMessage());
            return Result.error(400,error);
        }
        return Result.error(400,"请求参数格式错误" + ex.getMessage());
    }

    /**
     * 处理SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(400,msg);
        }else{
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
